/**
 * 名晟中鑫是一家专业数字化、智慧化研发和运营的服务提供商，公司本着“星火燎原、创新创业、科技顶天、服务立地”的发展理念，
 * 致力于新型智慧城市的建设和运营，业务包括智慧城市顶层设计咨询、互联网+、智慧政务、智慧医疗、智慧社区、智慧交通、智慧农业、智慧教育、智慧应急等。
 * 积极构建以政府为主导，企业和市民为主体、市场为导向、产学研相结合的推进体系，资源有效整合与共享，不断增强建设智慧城市建设的整体合力，
 * 真正推动民众生存智慧化。
 **/
package com.zj.config;

import org.apache.http.client.ConnectionBackoffStrategy;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName RestTemplateConfig
 * @Description resttemplate
 * @createTime 2024年11月19日 21:25
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory httpRequestFactory(){
        return new HttpComponentsClientHttpRequestFactory(http());
    }

    @Bean
    public HttpClient http(){
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(500);//连接池最大500链接
        //对maxTotal的细分，每个主机最大并发是300
        //只请求a.com则最大并发为300
        //请求a.com;最大并发300,b.com最大并发300，但是达不到，因为maxTotal是500
        connectionManager.setDefaultMaxPerRoute(300);//最大路由数
        //request配置
        RequestConfig requestConfig = RequestConfig.custom()
                //返回数据的超时时间
                .setSocketTimeout(50000)
                //链接上服务器的超时时间
                .setConnectTimeout(1000)
                //从连接池中获取链接的超时时间
                .setConnectionRequestTimeout(1000).build();
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }
}
